# coding:utf-8
import json
import os
import base64
import time
import random
import urllib
from datetime import datetime, date
from io import BytesIO

from PIL import Image
from flask import request, current_app, jsonify
from flask_restful import Api, Resource

from app.enterprise.models import EnterpriseHomepage
from app.utils import get_root_host_name
from app.api.qt_schemas import condition_schema
from app.compute.compute_process import ApiProcess
from app.exceptions import NotProductError, InputError
from app.msg.utils import generate_sms_content
from common.im_util import im_client, CS_ACCID
from .. import db
from app.api.utils import (
    generate_captcha, generate_demand_list_json, get_kf_virtual_num_list
)
from app.token import AuthToken
from app.op.models import (
    User, Demand, Area, UserInfo,
    DemandFinishImg, Partic, Pack, UserTag, DemandClient
)
from app.op.constant import (
    default_demand_params, UserType, DemandStatus, DemandColor,
    default_demand_rent_params, DemandCate, DemandSurr, DemandSource,
    DemandFinishImgState, ParticStatus, UserActive, UserStatus, DemandClientSource)
from app.ccws.models import create_outbound_mission
from app.ccws.constant import CallReason
from .supplier_schemas import (
    demand_create_schema, demand_edit_schema, demand_activate_schema)
from .client_schemas import (
    demand_img_schema, draft_demand_edit_schema, client_consult_schema,
    certify_sup_cnt_schema, supplier_info_in_schema, supplier_info_out_schema,
    finish_img_list_schema, partic_info_list_schema, supplier_partic_list_in_schema,
    supplier_list_in_schema, supplier_list_out_schema)
from .constant import TOKEN_TIMEOUT
from .views import AuthResource, Response
from .utils import generate_demand_info_json, draft_extra_handle
from .codes import SUCCESS, UNAUTHORIZED, PARAMS_ILLEGAL, USER_NOT_EXIST
from .supplier_codes import (
    DEMAND_NOT_SELF, DEMAND_DISABLE_EDIT, DEMAND_NOT_EXIST, DEMAND_DISABLE_ACTIVATE,
    DEMAND_POST_DUPLICATE
)
from app.wph_lib import alidayu
from app.msg.models import SMSLog
from app.auth.constant import CaptchaSmsChannel
from common.constant import Captcha_Sms_Channel_Key

api = Api()


@api.resource('/Client/Demand/getList4CurrUser')
class CurrUserDemandResource(AuthResource):
    """
    created by chenhj at 2017/8/14
    获取当前用户的需求列表（不含草稿）
    """
    def post(self):
        """
        created by chenhj at 2017/8/14

        """
        return Response(SUCCESS, {
            'list': generate_demand_list_json(
                self.user.get_all_valid_demands(), self.user
            ),
        })


@api.resource('/Client/Demand/postDraft')
class PostDraftDemandResource(Resource):
    """
    created by chenhj at 2017/8/15
    发布需求(草稿)
    """

    def post(self):
        """
        created by chenhj at 2017/8/15
        add by zhouhl 2017-08-23 即官网留电后调用的接口，与外呼队列联动
        """
        data, errors = demand_create_schema.load(request.form)
        if errors:
            return Response(PARAMS_ILLEGAL.new_format_msg(list(errors.values())[0][0]))

        mobile = data['mobile']
        user = User.get_by_args(mobile=mobile)
        area_id = Area.get_area_id(data['prov'], data['city'])
        # 若用户不存在, 则创建用户
        if not user:
            if 'nickname' in data and data['nickname']:
                nickname = data['nickname']
            else:
                nickname = '万屏汇客户'
            user = User.create(
                mobile=mobile,
                nickname=nickname,
                prov=data['prov'],
                city=data['city'],
                area_id=area_id,
                type=UserType.CLIENT.value
            )

        # 若该用户当天已留过电, 且后台未处理(草稿状态), 则不再生成草稿订单
        today = date.today()
        start_date = datetime(today.year, today.month, today.day)
        start = start_date.strftime('%s')
        end = time.time()
        hostname = get_root_host_name(request.referrer)
        enterprise_homepage = EnterpriseHomepage.get_by_args(hostname=hostname)
        exist_demand = Demand.query.filter(
            Demand.status.in_([DemandStatus.DRAFT.value, DemandStatus.UNCHECKED.value]),
            Demand.created_at.between(start, end),
            Demand.uid == user.id
        ).first()
        if exist_demand:
            print('duplicated mobile: {}'.format(mobile))
            DemandClient.visit(
                user.id, DemandClientSource.LEAVE_MOBILE.value,
                sem_referer=request.referrer,
                sem_origin_url='' if 'sem' not in data or not data['sem'] else json.loads(data['sem']).get('UrlReferrer', ''),
                enterprise_id=enterprise_homepage.enterprise_id if enterprise_homepage else 0,
                enterprise_source=data.get('enterprise_source', '')
            )
            return Response(DEMAND_POST_DUPLICATE)

        # 创建需求
        demand = Demand.create(
            uid=user.id,
            area_id=area_id,
            cate=data['cate'],
            prov=data['prov'],
            city=data['city'],
            sem=data['sem'] if 'sem' in data else None,
            malf=data.get('malf', 0),
            type=data.get('type', 0),
            surr=data.get('surr', 0),
            color=data.get('color', 0),
            span=data.get('span', ''),
            source=DemandSource.LIUDIAN.value,
            ip=request.remote_addr,
            enterprise_id=enterprise_homepage.enterprise_id if enterprise_homepage else 0
        )

        DemandClient.visit(
            user.id, DemandClientSource.LEAVE_MOBILE.value,
            sem_referer=request.referrer,
            sem_origin_url='' if not demand.sem else json.loads(demand.sem).get('UrlReferrer', ''),
            enterprise_id=enterprise_homepage.enterprise_id if enterprise_homepage else 0,
            enterprise_source=data.get('enterprise_source', '')
        )

        resp = jsonify(Response(SUCCESS, {
            'id': demand.id
        }))

        # 官网留电增加外呼任务
        if draft_extra_handle(resp, demand):
            tmp_outbound_record, err = create_outbound_mission(
                mobile=user.mobile,
                call_reason=CallReason.LEAVE_CALLBACK.value,
                schedule_time=datetime.now(),
                user_id=user.id
            )
            if tmp_outbound_record:
                db.session.add(tmp_outbound_record)

        print('success create demand')
        return resp


@api.resource('/Client/Demand/ie8/postDraft')
class IE8PostDraftDemandResource(Resource):
    """
    created by chenhj at 2017/8/15
    发布需求(草稿)
    """

    def post(self):
        """
        created by chenhj at 2017/8/15
        add by zhouhl 2017-08-23 即官网留电后调用的接口，与外呼队列联动
        """

        post_data = request.data.decode('utf8')
        split_data = post_data.split('&', 1)

        print('ie8 postDraft...')

        first_data = split_data[0].split('=', 1)
        second_data = split_data[1].split('=', 1)
        if first_data[0] == 'mobile':
            mobile = first_data[1]
        elif second_data[0] == 'mobile':
            mobile = second_data[1]

        if first_data[0] == 'sem':
            sem = first_data[1]
        elif second_data[0] == 'sem':
            sem = second_data[1]
        if sem:
            sem = urllib.parse.unquote_plus(sem)

        user = User.get_by_args(mobile=mobile)
        area_id = '542500'
        # 若用户不存在, 则创建用户
        # FIXME by chenhj at 2017/12/1 通过这个接口过来的统一到阿里地区
        if not user:
            user = User.create(
                mobile=mobile,
                nickname='万屏汇客户',
                prov='西藏自治区',
                city='阿里地区',
                area_id=area_id,
                type=UserType.CLIENT.value
            )

        # 若该用户当天已留过电, 且后台未处理(草稿状态), 则不再生成草稿订单
        today = date.today()
        start_date = datetime(today.year, today.month, today.day)
        start = start_date.strftime('%s')
        end = time.time()
        exist_demand = Demand.query.filter(
            Demand.status.in_([DemandStatus.DRAFT.value, DemandStatus.UNCHECKED.value]),
            Demand.created_at.between(start, end),
            Demand.uid == user.id
        ).first()
        if exist_demand:
            print('ie8 duplicated mobile: {}'.format(mobile))
            DemandClient.visit(
                user.id, DemandClientSource.LEAVE_MOBILE.value,
                sem_referer=request.referrer,
                sem_origin_url='' if not sem else json.loads(sem).get('UrlReferrer', '')
            )
            return Response(DEMAND_POST_DUPLICATE)

        # 创建需求
        demand = Demand.create(
            uid=user.id,
            area_id=area_id,
            cate=1,
            prov='西藏自治区',
            city='阿里地区',
            sem=sem or None,
            ip=request.remote_addr,
            source=DemandSource.LIUDIAN.value
        )
        DemandClient.visit(
            user.id, DemandClientSource.LEAVE_MOBILE.value,
            sem_referer=request.referrer,
            sem_origin_url='' if not sem else json.loads(sem).get('UrlReferrer', '')
        )

        resp = jsonify(Response(SUCCESS, {
            'id': demand.id
        }))

        # 官网留电增加外呼任务
        if draft_extra_handle(resp, demand):
            tmp_outbound_record, err = create_outbound_mission(
                mobile=user.mobile,
                call_reason=CallReason.LEAVE_CALLBACK.value,
                schedule_time=datetime.now(),
                user_id=user.id
            )
            if tmp_outbound_record:
                db.session.add(tmp_outbound_record)

        print('success create demand')
        return resp


@api.resource('/Client/Demand/prePost')
class PrePostDemandResource(Resource):
    """
    created by chenhj at 2017/8/15
    预发布需求
    """

    def post(self):
        data, errors = demand_create_schema.load(request.form)
        if errors:
            return Response(PARAMS_ILLEGAL.new_format_msg(list(errors.values())[0][0]))

        token = request.cookies.get('opc_token')
        user = AuthToken.verify_auth_token(token)
        area_id = Area.get_area_id(data['prov'], data['city'])
        # 如果已登录, 则直接用此用户的uid去创建项目(忽略传入的手机号)
        if user:
            today = date.today()
            start_date = datetime(today.year, today.month, today.day)
            start = start_date.strftime('%s')
            end = time.time()
            hostname = get_root_host_name(request.referrer)
            enterprise_homepage = EnterpriseHomepage.get_by_args(hostname=hostname)
            exist_demand = Demand.query.filter(
                Demand.status.in_([DemandStatus.DRAFT.value, DemandStatus.UNCHECKED.value]),
                Demand.created_at.between(start, end),
                Demand.uid == user.id
            ).first()
            if exist_demand:
                print('duplicated user: {}'.format(user.id))
                DemandClient.visit(
                    user.id, DemandClientSource.LEAVE_MOBILE.value,
                    sem_referer=request.referrer,
                    sem_origin_url='' if 'sem' not in data or not data['sem'] else json.loads(data['sem']).get('UrlReferrer', ''),
                    enterprise_id=enterprise_homepage.enterprise_id if enterprise_homepage else 0,
                    enterprise_source=data.get('enterprise_source', '')
                )
                return Response(DEMAND_POST_DUPLICATE)

            # 创建需求
            demand = Demand.create(
                uid=user.id,
                area_id=area_id,
                cate=data['cate'],
                prov=data['prov'],
                city=data['city'],
                ip=request.remote_addr,
                sem=data['sem'] if 'sem' in data else None,
                source=DemandSource.LIUDIAN.value,
                enterprise_id=enterprise_homepage.enterprise_id if enterprise_homepage else 0
            )

            DemandClient.visit(
                user.id, DemandClientSource.LEAVE_MOBILE.value,
                sem_referer=request.referrer,
                sem_origin_url='' if not demand.sem else json.loads(demand.sem).get('UrlReferrer', ''),
                enterprise_id=enterprise_homepage.enterprise_id if enterprise_homepage else 0,
                enterprise_source=data.get('enterprise_source', '')
            )

            resp = jsonify(Response(SUCCESS, {
                'id': demand.id
            }))

            # 官网留电增加外呼任务
            if draft_extra_handle(resp, demand):
                tmp_outbound_record, err = create_outbound_mission(
                    mobile=user.mobile,
                    call_reason=CallReason.LEAVE_CALLBACK.value,
                    schedule_time=datetime.now(),
                    user_id=user.id
                )
                if tmp_outbound_record:
                    db.session.add(tmp_outbound_record)
            return resp

        # 未登录, 但已注册, 则返回401, 且调用发短信验证码功能
        mobile = data['mobile']
        user = User.get_by_args(mobile=mobile)
        if user:
            captcha_sms_channel = current_app.redis.get(Captcha_Sms_Channel_Key) or CaptchaSmsChannel.MENG_WANG.value

            key = 'captcha_{}'.format(mobile)
            captcha = current_app.redis.get(key)
            if not captcha:
                if captcha_sms_channel == CaptchaSmsChannel.NA.value:
                    captcha = '1234'
                else:
                    captcha = generate_captcha()
                current_app.redis.set(key, captcha, ex=30 * 60)

            template_code = 'NA'
            if captcha_sms_channel == CaptchaSmsChannel.MENG_WANG.value:
                template_code = 'CAPTCHA'
                content = generate_sms_content(
                    template_code=template_code,
                    captcha=captcha
                )
                current_app.captcha_producer.send(
                    json.dumps({
                        'mobile': mobile,
                        'content': content,
                    })
                )
            elif captcha_sms_channel == CaptchaSmsChannel.ALI_DA_YU.value:
                # 使用阿里大于发送短信
                template_code = 'SMS_52355022'
                req = alidayu.api.AlibabaAliqinFcSmsNumSendRequest()
                req.set_app_info(
                    alidayu.appinfo('23382326', 'd6932553edc60a55fdd84e6efb1bd262'))
                req.sms_type = 'normal'
                req.rec_num = mobile
                req.sms_template_code = template_code
                req.sms_free_sign_name = 'LED屏'
                req.sms_param = {'captcha': captcha}
                req.getResponse()

            SMSLog.create(
                mobile=mobile,
                template_code=template_code,
                content=captcha,
            )

            return Response(UNAUTHORIZED)

        # 未登录, 未注册, 则创建用户, 创建需求
        user = User.create(
            mobile=mobile,
            nickname='万屏汇客户',
            prov=data['prov'],
            city=data['city'],
            area_id=area_id,
            type=UserType.CLIENT.value
        )

        hostname = get_root_host_name(request.referrer)
        enterprise_homepage = EnterpriseHomepage.get_by_args(hostname=hostname)
        # 创建需求
        demand = Demand.create(
            uid=user.id,
            area_id=area_id,
            cate=data['cate'],
            prov=data['prov'],
            city=data['city'],
            sem=data['sem'] if 'sem' in data else None,
            ip=request.remote_addr,
            enterprise_id=enterprise_homepage.enterprise_id if enterprise_homepage else 0
        )

        DemandClient.visit(
            user.id, DemandClientSource.LEAVE_MOBILE.value,
            sem_referer=request.referrer,
            sem_origin_url='' if not demand.sem else json.loads(demand.sem).get('UrlReferrer', ''),
            enterprise_id=enterprise_homepage.enterprise_id if enterprise_homepage else 0,
            enterprise_source=data.get('enterprise_source', '')
        )
        resp = jsonify(Response(SUCCESS, {'id': demand.id}))

        # 官网留电增加外呼任务
        if draft_extra_handle(resp, demand):
            tmp_outbound_record, err = create_outbound_mission(
                mobile=user.mobile,
                call_reason=CallReason.LEAVE_CALLBACK.value,
                schedule_time=datetime.now(),
                user_id=user.id
            )
            if tmp_outbound_record:
                db.session.add(tmp_outbound_record)

        resp.set_cookie('opc_token', AuthToken.generate_auth_token(TOKEN_TIMEOUT, user))
        return resp


@api.resource('/Client/Demand/update')
class UpdateDemandResource(AuthResource):
    """
    created by chenhj at 2017/8/15
    修改需求
    """

    def post(self):
        data, errors = demand_edit_schema.load(request.form)
        if errors:
            return Response(PARAMS_ILLEGAL.new_format_msg(list(errors.values())[0][0]))

        demand = Demand.get_by_id(data['id'])
        if not demand:
            return Response(DEMAND_NOT_EXIST)

        if demand.uid != self.user.id:
            return Response(DEMAND_NOT_SELF)

        if demand.status not in (
            DemandStatus.DRAFT.value, DemandStatus.UNCHECKED.value, DemandStatus.ONGOING.value
        ):
            return Response(DEMAND_DISABLE_EDIT)

        demand.malf = data.get('malf', 0)
        demand.type = data['type']
        if 'surr' in data:
            demand.surr = data['surr']
        elif demand.cate in (DemandCate.INSTALL.value, DemandCate.MAINTAIN.value):
            demand.surr = default_demand_params[data['type']]['surr']
        else:
            # 租赁默认使用场地
            demand.surr = default_demand_rent_params['surr']
        demand.size = data.get('size', 0)
        demand.color = data['color']
        demand.span = data['span']
        demand.addr = data['addr']
        demand.budget = data.get('budget', 0)
        demand.remark = data.get('remark', '')

        return Response(SUCCESS, {
            'demand_info': generate_demand_info_json(demand, self.user)
        })


@api.resource('/Client/Demand/Draft/update')
class UpdateDraftDemandResource(Resource):
    """
    created by chenhj at 2017/10/17
    给用户修改项目信息, 无需登录
    """
    def post(self):
        data, errors = draft_demand_edit_schema.load(request.form)
        if errors:
            return Response(PARAMS_ILLEGAL.new_format_msg(list(errors.values())[0][0]))

        demand = Demand.get_by_id(data['demand_id'])
        if not demand:
            return Response(DEMAND_NOT_EXIST)

        user = User.get_by_id(demand.uid)

        if demand.status not in (
            DemandStatus.DRAFT.value, DemandStatus.UNCHECKED.value, DemandStatus.ONGOING.value
        ):
            return Response(DEMAND_DISABLE_EDIT)

        if 'nickname' in data:
            user.nickname = data['nickname']
        if 'addr' in data:
            demand.addr = data['addr']
        area_id = Area.get_area_id(data['prov'], data['city'])
        if area_id:
            demand.area_id = area_id
        return Response(SUCCESS, {
            'demand_info': generate_demand_info_json(demand, user)
        })


@api.resource('/Client/Demand/activate')
class ActivateDemandResource(AuthResource):
    """
    created by chenhj at 2017/8/15
    激活（并修改）需求
    """

    def post(self):
        data, errors = demand_activate_schema.load(request.form)
        if errors:
            return Response(PARAMS_ILLEGAL.new_format_msg(list(errors.values())[0][0]))

        demand = Demand.get_by_id(data['id'])
        area_id = Area.get_area_id(data['prov'], data['city'])
        if not demand:
            return Response(DEMAND_NOT_EXIST)

        if demand.uid != self.user.id:
            return Response(DEMAND_NOT_SELF)

        if demand.status != DemandStatus.DRAFT.value:
            return Response(DEMAND_DISABLE_ACTIVATE)

        if data['nickname'] != self.user.nickname:
            self.user.nickname = data['nickname']

        demand.malf = data.get('malf', 0)
        demand.type = data['type']
        if 'surr' in data:
            demand.surr = data['surr']
        elif demand.cate in (DemandCate.INSTALL.value, DemandCate.MAINTAIN.value):
            demand.surr = default_demand_params[data['type']]['surr']
        else:
            demand.surr = default_demand_rent_params['surr']
        demand.size = data.get('size', 0)
        if 'color' in data:
            demand.color = data['color']
        elif demand.cate in (DemandCate.INSTALL.value, DemandCate.MAINTAIN.value):
            demand.color = default_demand_params[data['type']]['color']
        else:
            demand.color = default_demand_rent_params['color']
        if 'span' in data:
            demand.span = data['span']
        elif demand.cate in (DemandCate.INSTALL.value, DemandCate.MAINTAIN.value):
            demand.span = default_demand_params[data['type']]['span']
        else:
            demand.span = default_demand_rent_params['span']
        demand.prov = data['prov']
        demand.city = data['city']
        demand.area_id = area_id
        demand.addr = data.get('addr', '')
        demand.status = DemandStatus.UNCHECKED.value

        msg1 = '@{nickname}，您好，确认您的{surr}{cate}项目信息如下：预算{budget}，位置在{addr}，面积约{size}㎡，{color}，间距{span}。'
        msg2 = '@{nickname}，您可以上传工程场地图片，方便工程商提供更精准的报价。'
        msg3 = '我正在为您通知更多工程师与您洽谈。'
        im_client.single_send_text_msg(CS_ACCID, self.user.id, msg1.format(
            nickname=self.user.nickname,
            cate=DemandCate(demand.cate).display,
            budget=str(demand.budget) if demand.budget else '暂无',
            size=str(demand.size),
            span=demand.span,
            color=DemandColor(demand.color).display,
            addr='{prov}{city}{addr}'.format(prov=demand.prov, city=demand.city, addr=demand.addr),
            surr=DemandSurr(demand.surr).display
        ))
        im_client.single_send_text_msg(CS_ACCID, self.user.id, msg2.format(nickname=self.user.nickname))
        im_client.single_send_text_msg(CS_ACCID, self.user.id, msg3)

        return Response(SUCCESS, {
            'demand_info': generate_demand_info_json(demand, self.user)
        })


@api.resource('/Client/Img/uploadDemandImg')
class DemandImgResource(AuthResource):
    """
    created by chenhj at 2017/8/21
    以base64编码形式上传项目图片
    """
    def post(self):
        """
        created by chenhj at 2017/8/21

        """
        data, errors = demand_img_schema.load(request.form)
        if errors:
            return Response(PARAMS_ILLEGAL.new_format_msg(list(errors.values())[0][0]))

        demand = Demand.get_by_id(data['demand_id'])
        if not demand:
            return Response(DEMAND_NOT_EXIST)
        if demand.uid != self.user.id:
            return Response(DEMAND_NOT_SELF)

        im = Image.open(BytesIO(base64.b64decode(data['img'])))
        path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'img/demand')
        filename = '{filename}.{format}'.format(
            format=im.format.lower(), filename=demand.id
        )
        im.save('{path}/{filename}'.format(path=path, filename=filename), im.format)

        demand.img = 'demand/{filename}?{timestamp}'.format(
            filename=filename, timestamp=int(time.time())
        )
        return Response(SUCCESS, {
            'img': demand.img_url
        })


@api.resource('/Client/Img/uploadDemandImgFile')
class DemandImgFileResource(AuthResource):
    """
    created by chenhj at 2017/8/21
    以文件形式上传项目图片
    """
    def post(self):
        """
        created by chenhj at 2017/8/21

        """
        demand_id = request.args['demand_id']

        demand = Demand.get_by_id(demand_id)
        if not demand:
            return Response(DEMAND_NOT_EXIST)
        if demand.uid != self.user.id:
            return Response(DEMAND_NOT_SELF)

        file = request.files['img']
        ext = file.filename.split('.')[-1]
        path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'img/demand')
        filename = '{filename}.{format}'.format(
            format=ext, filename=demand.id
        )
        file.save(os.path.join(path, filename))

        demand.img = 'demand/{filename}?{timestamp}'.format(
            filename=filename, timestamp=int(time.time())
        )
        return Response(SUCCESS, {
            'img': demand.img_url
        })


@api.resource('/Client/consult')
class ClientConsultResource(Resource):
    """
    created by chenhj at 2017/11/13
    客户咨询工程商, 工程商的咨询次数加1
    """
    def post(self):
        data, errors = client_consult_schema.load(request.get_json())
        if errors:
            return Response(PARAMS_ILLEGAL.new_format_msg(list(errors.values())[0][0]))

        supplier = User.get_by_id(data['supplier_id'])
        if not supplier:
            return Response(USER_NOT_EXIST)

        supplier_info = UserInfo.default_user_info(supplier.id)
        supplier_info.consult_count += 1

        return Response()


@api.resource('/Client/getCertifySupplierCntByCity')
class CitySupCntResource(Resource):
    """
    created by chenhj at 2017/11/13
    取某个城市下的认证工程商数
    """
    def post(self):
        data, errors = certify_sup_cnt_schema.load(request.get_json())
        if errors:
            return Response(PARAMS_ILLEGAL.new_format_msg(list(errors.values())[0][0]))
        return Response(SUCCESS, {
            'cnt': User.get_certify_sup_count_by_city(data['city_id']),
        })


@api.resource('/Client/getSupplierInfo')
class SupplierInfoResource(Resource):
    """
    created by chenhj at 2017/11/13
    查看工程商详情信息
    """
    def post(self):
        """
        created by chenhj at 2017/11/13

        """
        data, errors = supplier_info_in_schema.load(request.get_json())
        if errors:
            return Response(PARAMS_ILLEGAL.new_format_msg(list(errors.values())[0][0]))

        supplier = User.get_by_id(data['supplier_id'])
        if not supplier:
            return Response(USER_NOT_EXIST)

        num_list = get_kf_virtual_num_list()
        mobile = random.choice(num_list)

        dump_data = supplier_info_out_schema.dump(supplier)[0]
        dump_data['mobile'] = mobile

        #area_id = supplier.pack.area_id
        area_id = [i.id for i in supplier.attention_areas]
        area_id.sort(key=lambda x: x != data['city_id'])
        # 把前端传入的city_id放到最前
        locate_city = Area.get_by_id(data['city_id'])
        areas = Area.get_list_by_ids(area_id[:10])
        dump_data['area_name_list'] = [x.name for x in areas]
        dump_data['area_name_list'].sort(key=lambda x: x != locate_city.name)

        # 精彩案例(取最新3个)
        finished_img_data = DemandFinishImg.query.filter(
            DemandFinishImg.deleted_at == 0,
            DemandFinishImg.user_id == supplier.id,
            DemandFinishImg.state == DemandFinishImgState.CHECKED.value
        ).join(
            Demand, Demand.id == DemandFinishImg.demand_id
        ).filter(
            Demand.status == DemandStatus.DONE.value
        ).with_entities(
            DemandFinishImg.img, Demand.city, Demand.cate, Demand.type,
            Demand.surr, Demand.size, Demand.color, Demand.span,
            Demand.addr, DemandFinishImg.created_at
        ).order_by(DemandFinishImg.created_at.desc()).limit(3)
        dump_data['outstanding_cases'] = finish_img_list_schema.dump(finished_img_data)[0]

        host = os.environ.get('img_host')
        for each in dump_data['outstanding_cases']:
            each['img'] = urllib.parse.urljoin(host, each['img'])

        # 成交记录(取最新5个)
        partic_data = Partic.query.filter(
            Partic.supplier_id == supplier.id,
            Partic.status == ParticStatus.SUCCEED.value,
            Partic.feedback_status == 0,
            Partic.is_revert.is_(False),
            Partic.deleted_at == 0,
        ).join(
            Demand, Demand.id == Partic.demand_id
        ).join(
            User, User.id == Demand.uid
        ).with_entities(
            Partic.id.label('partic_id'), Demand.city, Demand.cate, User.nickname,
            Demand.surr, Demand.size, Demand.color, Demand.span,
            Demand.addr, Demand.published_at, Demand.type,
        ).order_by(Partic.created_at.desc()).limit(5)
        dump_data['partic_list'] = partic_info_list_schema.dump(partic_data)[0]

        return Response(SUCCESS, {
            'supplier_info': dump_data
        })


@api.resource('/Client/getSupplierParticList')
class SupplierParticListResource(Resource):
    """
    created by chenhj at 2017/11/13
    查看工程商成交记录
    """
    def post(self):
        """
        created by chenhj at 2017/11/13

        """
        data, errors = supplier_partic_list_in_schema.load(request.get_json())
        if errors:
            return Response(PARAMS_ILLEGAL.new_format_msg(list(errors.values())[0][0]))

        supplier = User.get_by_id(data['supplier_id'])
        if not supplier:
            return Response(USER_NOT_EXIST)

        # 成交记录(取最新5个)
        partic_data = Partic.query.filter(
            Partic.supplier_id == supplier.id,
            Partic.status == ParticStatus.SUCCEED.value,
            Partic.feedback_status == 0,
            Partic.is_revert.is_(False),
            Partic.deleted_at == 0,
            Partic.id < data['partic_id']
        ).join(
            Demand, Demand.id == Partic.demand_id
        ).join(
            User, User.id == Demand.uid
        ).with_entities(
            Partic.id.label('partic_id'), Demand.city, Demand.cate, User.nickname,
            Demand.surr, Demand.size, Demand.color, Demand.span,
            Demand.addr, Demand.published_at, Demand.type,
        ).order_by(Partic.created_at.desc()).limit(5)
        partic_list = partic_info_list_schema.dump(partic_data)[0]

        return Response(SUCCESS, {
            'partic_list': partic_list
        })


@api.resource('/Client/getSupplierList')
class SupplierListResource(Resource):
    """
    created by chenhj at 2017/11/13
    工程商列表
    """
    def post(self):
        data, errors = supplier_list_in_schema.load(request.get_json())
        if errors:
            return Response(PARAMS_ILLEGAL.new_format_msg(list(errors.values())[0][0]))

        # NOTE by zhouhl 重写此查询，改用中间表
        # query = User.query.filter(
        #     User.deleted_at == 0,
        #     User.black.is_(False),
        #     User.active == UserActive.ACTIVE.value,
        #     User.type == UserType.ENGINEER.value,
        #     User.status == UserStatus.PASS.value,
        #     User.is_internal.is_(False),
        #     User.is_virt.is_(False)
        # ).join(
        #     UserInfo, UserInfo.user_id == User.id
        # ).join(
        #     UserTag, UserTag.user_id == User.id
        # ).join(
        #     Pack, Pack.uid == User.id
        # ).filter(
        #     db.func.json_contains(Pack.area_id, str(data['city_id']))
        # )

        # 改用用户关注地区中间表后的代码
        tmp_area = Area.get_by_id(data['city_id'])
        query = tmp_area.area_users.filter(
            User.deleted_at == 0,
            User.black.is_(False),
            User.active == UserActive.ACTIVE.value,
            User.type == UserType.ENGINEER.value,
            User.status == UserStatus.PASS.value,
            User.is_internal.is_(False),
            User.is_virt.is_(False)
        ).join(
            UserInfo, UserInfo.user_id == User.id
        ).join(
            UserTag, UserTag.user_id == User.id
        ).join(
            Pack, Pack.uid == User.id
        )

        if data['cate'] == DemandCate.INSTALL.value:
            query = query.filter(
                UserTag.install.is_(True)
            )
        elif data['cate'] == DemandCate.MAINTAIN.value:
            query = query.filter(
                UserTag.repair.is_(True)
            )
        elif data['cate'] == DemandCate.RENT.value:
            query = query.filter(
                UserTag.rent.is_(True)
            )
        query = query.order_by(
            UserInfo.bid_count.desc(),
            UserInfo.user_id.asc()
        ).paginate(
            data['current_page'], per_page=36, error_out=False
        )
        dump_data = supplier_list_out_schema.dump(query.items)[0]
        num_list = get_kf_virtual_num_list()
        mobile = random.choices(num_list, k=len(dump_data))
        for i, user in enumerate(dump_data):
            user['mobile'] = mobile[i]
        return Response(SUCCESS, {
            'user_list': dump_data,
            'current_page': data['current_page'] if dump_data else query.pages
        })


@api.resource('/Client/compute/prices')
class ClientComputePrices(Resource):
    """
    create by ld_wu 2017-09-18
    客户获取工程商报价接口
    """

    def post(self):
        data, errors = condition_schema.load(request.get_json() or dict())
        if errors:
            return Response(
                PARAMS_ILLEGAL.new_format_msg(list(errors.values())[0][0])
            )
        try:
            compute_obj = ApiProcess(data, is_client=True)
            prices, total = compute_obj.client_quotation_models()
        except (NotProductError, InputError) as e:
            # 产品库报错则为议价
            total = 0

        return Response(
            SUCCESS,
            dict(
                total=int(total)
            )
        )
